<script setup>

import local from '@/axios/local'
import {onMounted, reactive, ref} from "vue";
import {invoke} from "@/utils/ipc_fn";
import {ElMessage} from "element-plus";
import * as uuid from "uuid";

const params = reactive({
  type: '',
  order: '',
  cate: '',
  resolution: '',
  page: 1,
  search: '',
  total: 0,
})
const selectList = ref([])
const resolution = [
  {
    label: 'Ultra HD',
    options: [
      {
        label: '3840x2160',
        desc: '4K Ultra HD'
      },
      {
        label: '7680x4320',
        desc: '8K Ultra HD'
      },
    ]
  },
  {
    label: 'Apple',
    options: [
      {
        label: '1242x2688',
        desc: 'iphone XS Max'
      },
      {
        label: '1125x2436',
        desc: 'iphone X / XS'
      },
      {
        label: '1080x1920',
        desc: 'iPhone 6S+/7+/8+'
      },
      {
        label: '750x1334',
        desc: 'iPhone 6/6S/7/8'
      },
    ]
  },
  {
    label: 'Android Device',
    options: [
      {
        label: '1440x2960',
        desc: '1440x2960 QHD'
      },
      {
        label: '1440x2560',
        desc: '1440x2560 QHD'
      },
      {
        label: '1080x1920',
        desc: '1080x1920 Full HD'
      },
      {
        label: '720x1280',
        desc: '720x1280 HD'
      },
    ]
  },
  {
    label: 'Widescreen',
    options: [
      {
        label: '2560x1440',
        desc: '2560x1440 QHD'
      },
      {
        label: '1920x1080',
        desc: '1920x1080 Full HD'
      },
      {
        label: '1366x768',
        desc: '1366x768',
      },
      {
        label: '1280x720',
        desc: '1280x720',
      },
    ]
  }
]
const screenList = ref([])
const tabList = [
  {
    name: '所有壁纸',
    value: '',
    cols: 6
  },
  {
    name: '电脑壁纸',
    value: '/for_desktop',
    cols: 6
  },

  {
    name: '手机壁纸',
    value: '/for_mobile',
    cols: 6
  }
]
const dataList = ref([])
const dataList_copy = ref([])
const scrollbarMobile = ref()

async function scrollToEnd(e) {
  let index = tabList.findIndex(el => el.value === params.type)
  const scrollElement = scrollbarMobile.value[index].$el.querySelector('.el-scrollbar__wrap');  // 获取滚动区域
  const isAtBottom = scrollElement.scrollTop + scrollElement.clientHeight >= scrollElement.scrollHeight;

  if (isAtBottom) {
    console.log("已滚动到底部！");
    await getData(params.page + 1)
  }
}

function toDownload(item) {
  invoke('selectFolder', '').then(async r => {
    if (!r) return
    await local.post('/wallpaper/downloadToDir', {
      savePath: r + '/' + uuid.v4().replaceAll('-', '') + '.png',
      url: item.download_url
    })
    ElMessage.success('下载成功')
  })
}

async function setWallpaper(item, index) {
  console.log(item, 'item')
  if (index === 'all') {
    index = []
    for (let k in screenList.value) {
      index.push(k)
    }
  }
  await local.post('/wallpaper/setWallpaper', {
    url: item.download_url,
    index
  })
  ElMessage.success('设置成功')
}

function search() {
  dataList.value = []
  dataList_copy.value = []
  getData(1)
}

function splitArrayEvenly(arr) {
  let item = tabList.find(el => el.value === params.type)

  const result = [];
  let len = (24 / item.cols)
  for (let k = 0; k < len; k++) {
    result.push([])
  }
  arr.forEach((item, index) => {
    result[index % len].push(item);  // 将元素按照 index 取余后分配到不同的组
  });
  return result;
}

async function getData(page) {
  if (page) {
    params.page = page
  }
  let {data,select} = await local.get('/wallpaper/getPageData', {params})
  await local.get('/os/getScreen')
  selectList.value = select
  dataList_copy.value = dataList_copy.value.concat(data)
  dataList.value = splitArrayEvenly(JSON.parse(JSON.stringify(dataList_copy.value)))
}

async function tabChange() {
  params.page = 1
  dataList.value = []
  dataList_copy.value = []
  await getData()
}
onMounted(async ()=>{
  await getData()
  await invoke('getScreen', 2, (r => {
    if (r.code === 200) {
      screenList.value = r.data
    }
    console.log(r)
  }))
})


</script>

<template>
  <div class="wallpaper">
    <div class="search">
      <el-input style="flex: 1;flex-shrink: 0;overflow: hidden" clearable v-model="params.search"
                placeholder="搜点什么..." type="text"></el-input>
      <el-button type="primary" style="margin-left: 30px" @click="search">搜索</el-button>
      <el-radio-group @change="search" style="margin-left: 30px;display: flex" v-model="params.order" size="small">
        <el-radio-button label="最新" value=""/>
        <el-radio-button label="人气" value="popular"/>
      </el-radio-group>
      <el-select clearable filterable @change="search" size="small" v-model="params.cate" placeholder="分类"
                 style="margin-left: 30px;width: 100px;">
        <el-option
            v-for="item in selectList"
            :key="item"
            :label="item.label"
            :value="item.value"
        >
        </el-option>
      </el-select>
      <el-select clearable filterable @change="search" size="small" v-model="params.resolution" placeholder="分辨率"
                 style="margin-left: 30px;width: 200px;">
        <el-option-group
            v-for="group in resolution"
            :key="group.label"
            :label="group.label"
        >
          <el-option
              v-for="item in group.options"
              :key="item.value"
              :value="item.label"
          >
            <p>{{ item.label }}<span style="font-size: 12px;color: gray">（{{ item.desc }}）</span></p>
          </el-option>
        </el-option-group>
      </el-select>
    </div>

    <el-tabs @tab-change="tabChange" v-model="params.type" class="demo-tabs">
      <el-tab-pane :label="tab.name" :name="tab.value" v-for="tab in tabList" :key="tab.value">
        <div class="wallpaper-ul mobile-ul">
          <el-scrollbar ref="scrollbarMobile" @scroll="scrollToEnd">
            <el-row>
              <el-col v-for="(item,index ) in dataList" :key="index" :span="tab.cols">
                <div class="wallpaper-li " v-for="(it,i) in item" :key="i">
                  <el-dropdown trigger="contextmenu">
                    <el-image class="mobile" :title="it.title" :src="it.src" :alt="it.title"
                              :preview-src-list="[it.download_url]"></el-image>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="toDownload(it)">下载</el-dropdown-item>
                        <el-dropdown-item v-for="(screen,i) in screenList" :key="i" @click="setWallpaper(it,[i])">
                          {{ `设为桌面壁纸(${screen.label})` }}
                        </el-dropdown-item>
                        <el-dropdown-item v-if="screenList.length>1" @click="setWallpaper(it,'all')">
                          {{ `设为桌面壁纸(全部显示屏)` }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>

                </div>
              </el-col>
            </el-row>
          </el-scrollbar>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
.search {
  display: flex;
  align-items: center;

}

::v-deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column-reverse;

  .el-tabs__header {
    margin-bottom: 10px;
  }

  .el-tabs__content {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .el-scrollbar__viewm, .el-row {
      height: 100%;
    }

    .el-tab-pane {
      height: 100%;

      .el-scrollbar {
        flex: 1;
        flex-shrink: 0;
        overflow: hidden;

        .el-scrollbar__view {
          display: flex;
          flex-direction: column;
        }
      }
    }
  }
}

.wallpaper {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px;
  box-sizing: border-box;
}

.pagination {
  display: flex;
  justify-content: center;
}

.wallpaper-ul {
  height: 100%;
  box-sizing: border-box;
  width: 100%;
  display: flex;
  flex-direction: column;

  .wallpaper-li {
    .mobile {
      width: 100%;
      padding: 3px;
      height: auto;

      ::v-deep(.el-image__preview) {
        width: 100%;
        height: auto;
        border-radius: 5px;
        transition: transform 0.5s ease; /* 动画过渡效果 */
        &:hover {
          transform: scale(1.5); /* 放大 1.2 倍 */
        }
      }
    }

    img {
      padding: 3px;
      cursor: pointer;
      width: 100%;
      height: 150px;

    }
  }
}
</style>